const request = require('../../utils/request')
const eventBus = require('../../utils/eventBus')

Page({
  data: {
    pointsInfo: {
      totalPoints: 0,
      availablePoints: 0,
      usedPoints: 0
    },
    currentTab: 'all',
    filterOptions: [
      { label: '全部', value: 'all' },
      { label: '获取', value: 'earn' },
      { label: '消费', value: 'spend' }
    ],
    pointsHistory: [],
    filteredHistoryList: [],
    listHeight: 600
  },

  onLoad() {
    this.handlePointsUpdate = this.handlePointsUpdate.bind(this)
    eventBus.on('pointsUpdate', this.handlePointsUpdate)
    
    const systemInfo = wx.getSystemInfoSync()
    const listHeight = systemInfo.windowHeight - 350
    this.setData({ listHeight })
    
    this.fetchPointsOverview()
    this.fetchPointsHistory()
  },

  handlePointsUpdate() {
    this.fetchPointsOverview()
    this.fetchPointsHistory()
  },

  async fetchPointsOverview() {
    try {
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const { data } = await request({
        url: '/api/points/overview',
        data: { userId }
      })
      this.setData({ pointsInfo: data })
    } catch (error) {
      console.error('获取积分概览失败:', error)
      wx.showToast({
        title: '获取积分概览失败',
        icon: 'none'
      })
    }
  },

  async fetchPointsHistory() {
    try {
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const { data } = await request({
        url: '/api/points/history',
        data: { userId }
      })
      
      this.setData({ 
        pointsHistory: data 
      }, () => {
        this.updateFilteredList()
      })
    } catch (error) {
      console.error('获取积分历史失败:', error)
      wx.showToast({
        title: '获取积分历史失败',
        icon: 'none'
      })
    }
  },
  
  updateFilteredList() {
    const { currentTab, pointsHistory } = this.data
    
    const filteredList = currentTab === 'all' 
      ? pointsHistory 
      : pointsHistory.filter(item => item.type === currentTab)
      
    this.setData({ filteredHistoryList: filteredList })
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab }, () => {
      this.updateFilteredList()
    })
  },

  goToPointsMall() {
    wx.navigateTo({
      url: '/packageB/points-mall/index'
    })
  },

  onBack() {
    wx.navigateBack()
  },

  onUnload() {
    eventBus.off('pointsUpdate', this.handlePointsUpdate)
  },

  onShow() {
    const needUpdate = wx.getStorageSync('pointsNeedUpdate')
    if (needUpdate) {
      wx.removeStorageSync('pointsNeedUpdate')
      Promise.all([
        this.fetchPointsOverview(),
        this.fetchPointsHistory()
      ]).catch(console.error)
    }
  }
})